<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>java基础：iterator迭代器 | haijd</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  <meta name="keywords" content="Java基础" />
  
  
  
  
  <meta name="description" content="Iterator迭代器概述和应用">
<meta name="keywords" content="Java基础">
<meta property="og:type" content="article">
<meta property="og:title" content="Java基础：Iterator迭代器">
<meta property="og:url" content="http://www.hais2.com/2017/06/03/Java基础：Iterator迭代器/index.html">
<meta property="og:site_name" content="haijd">
<meta property="og:description" content="Iterator迭代器概述和应用">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://img.mp.sohu.com/upload/20170809/7f6678264b154d028f0e36e9159c8e9a.png">
<meta property="og:updated_time" content="2017-12-13T12:25:59.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java基础：Iterator迭代器">
<meta name="twitter:description" content="Iterator迭代器概述和应用">
<meta name="twitter:image" content="http://img.mp.sohu.com/upload/20170809/7f6678264b154d028f0e36e9159c8e9a.png">
  
    <link rel="alternate" href="/atom.xml" title="haijd" type="application/atom+xml">
  
  <link rel="icon" href="/css/images/favicon.ico">
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Montserrat:700" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic" rel="stylesheet" type="text/css">
  <link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
  <style type="text/css">
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/9749f0/00000000000000000001008f/27/l?subset_id=2&fvd=n5) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/90cf9f/000000000000000000010091/27/l?subset_id=2&fvd=n7) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/8a5494/000000000000000000013365/27/l?subset_id=2&fvd=n4) format("woff2");font-weight:lighter;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/d337d8/000000000000000000010095/27/l?subset_id=2&fvd=i4) format("woff2");font-weight:400;font-style:italic;}</style>
    
  <link rel="stylesheet" id="athemes-headings-fonts-css" href="//fonts.googleapis.com/css?family=Yanone+Kaffeesatz%3A200%2C300%2C400%2C700&amp;ver=4.6.1" type="text/css" media="all">
  <link rel="stylesheet" href="/css/style.css">

  <script src="/js/jquery-3.1.1.min.js"></script>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="/css/bootstrap.css" >
  <link rel="stylesheet" href="/css/hiero.css" >
  <link rel="stylesheet" href="/css/glyphs.css" >
  
    <link rel="stylesheet" href="/css/vdonate.css" >
  

</head>

<script>
var themeMenus = {};

  themeMenus["/"] = "Home"; 

  themeMenus["/archives"] = "Archives"; 

  themeMenus["/categories"] = "Categories"; 

  themeMenus["/tags"] = "Tags"; 

  themeMenus["/about"] = "About"; 

</script>


  <body data-spy="scroll" data-target="#toc" data-offset="50">


  <header id="allheader" class="site-header" role="banner">
  <div class="clearfix container">
      <div class="site-branding">

          <h1 class="site-title">
            
              <a href="/" title="haijd" rel="home"> haijd </a>
            
          </h1>

          
            <div class="site-description">Stay Hungry,Stay Foolish</div>
          
            
          <nav id="main-navigation" class="main-navigation" role="navigation">
            <a class="nav-open">Menu</a>
            <a class="nav-close">Close</a>
            <div class="clearfix sf-menu">

              <ul id="main-nav" class="nmenu sf-js-enabled">
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/">Home</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/archives">Archives</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/categories">Categories</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/tags">Tags</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/about">About</a> </li>
                    
              </ul>
            </div>
          </nav>


      </div>
  </div>
</header>




  <div id="container">
    <div id="wrap">
            
      <div id="content" class="outer">
        
          <section id="main" style="float:none;"><article id="post-Java基础：Iterator迭代器" style="width: 66%; float:left;" class="article article-type-post" itemscope itemprop="blogPost" >
  <div id="articleInner" class="clearfix post-1016 post type-post status-publish format-standard has-post-thumbnail hentry category-template-2 category-uncategorized tag-codex tag-edge-case tag-featured-image tag-image tag-template">
    
<div class="article-gallery">
  <div class="article-gallery-photos">
    
      <a class="article-gallery-img fancybox" href="http://img.mp.sohu.com/upload/20170809/7f6678264b154d028f0e36e9159c8e9a.png" rel="gallery_cjie4nahk004b3swakcrarlyg">
        <img src="http://img.mp.sohu.com/upload/20170809/7f6678264b154d028f0e36e9159c8e9a.png" itemprop="image">
      </a>
    
  </div>
</div>

    
      <header class="article-header">
        
  
    <h1 class="thumb" class="article-title" itemprop="name">
      Java基础：Iterator迭代器
    </h1>
  

      </header>
    
    <div class="article-meta">
      
	Posted on <a href="/2017/06/03/Java基础：Iterator迭代器/" class="article-date">
	  <time datetime="2017-06-03T11:43:42.000Z" itemprop="datePublished">June 3, 2017</time>
	</a>

      
	<span id="busuanzi_container_page_pv">
	  本文总阅读量<span id="busuanzi_value_page_pv"></span>次
	</span>

    </div>
    <div class="article-entry" itemprop="articleBody">
      
        <!-- TOC -->
<ul>
<li><a href="#迭代器的概述">迭代器的概述</a></li>
<li><a href="#迭代器的实现原理">迭代器的实现原理</a></li>
<li><a href="#迭代器代码实现">迭代器代码实现</a></li>
<li><a href="#迭代器的执行过程">迭代器的执行过程</a></li>
<li><a href="#集合迭代中的转型">集合迭代中的转型</a></li>
<li><a href="#foreach遍历数组">foreach遍历数组</a></li>
</ul>
<!-- /TOC -->
<h3 id="迭代器的概述"><a href="#迭代器的概述" class="headerlink" title="迭代器的概述"></a>迭代器的概述</h3><ul>
<li><p>迭代器概述:</p>
<ul>
<li><p>Java中有很多种集合，这些集合在存储元素的时候，存储的方式都是不尽相同的，那么对应的我们在取出元素的时候也不相同，为每一种集合设计一个取出方式显然是不合理的，所以就出现了一种屏蔽集合间差异的读取元素的方式，就是迭代器。</p>
</li>
<li><p>Collection集合元素的通用获取方式：在取元素之前先要判断集合中有没有元素，如果有，就把这个元素取出来，然后继续判断，如果有就继续取。一直把集合中的所有元素全部取出。这种取出方式专业术语称为迭代。</p>
</li>
<li><p>每种集合的底层的数据结构不同,例如ArrayList是数组,LinkedList底层是链表,但是无论使用那种集合,我们都会有判断是否有元素<br>以及取出里面的元素的动作,那么Java为我们提供一个迭代器定义了统一的判断元素和取元素的方法 。</p>
<a id="more"></a>
<h3 id="迭代器的实现原理"><a href="#迭代器的实现原理" class="headerlink" title="迭代器的实现原理"></a>迭代器的实现原理</h3></li>
</ul>
</li>
<li>迭代器的实现原理:Collection接口定义了一个方法<code>Iterator  iterator()</code>,实现类重写这个方法就可以返回一个实现<code>Iterator</code>接口的对象，该对象就可以对集合中的元素进行迭代。<ul>
<li>接口<code>Iterator</code> : 两个抽象方法<ul>
<li><code>boolean hasNext()</code> 判断集合中还有没有可以被取出的元素,如果有返回true</li>
<li><code>next()</code> 取出集合中的下一个元素</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3 id="迭代器代码实现"><a href="#迭代器代码实现" class="headerlink" title="迭代器代码实现"></a>迭代器代码实现</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">    Collection&lt;String&gt; coll = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">    coll.add(<span class="string">"123"</span>);</span><br><span class="line">    coll.add(<span class="string">"456"</span>);</span><br><span class="line">    coll.add(<span class="string">"789"</span>);</span><br><span class="line">    coll.add(<span class="string">"0"</span>);</span><br><span class="line">    <span class="comment">//调用集合的方法iterator()获取一个实现Iterator接口的对象，用来执行集合迭代</span></span><br><span class="line">    Iterator&lt;String&gt; it = coll.iterator();</span><br><span class="line">    <span class="comment">//使用循环判断集合中是否有元素，如果有就取出</span></span><br><span class="line">    <span class="keyword">while</span>(it.hasNext())&#123;</span><br><span class="line">        String s = it.next();</span><br><span class="line">        System.out.println(s);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//for (Iterator&lt;String&gt; it = coll.iterator(); it.hasNext();  ) &#123;</span></span><br><span class="line">    <span class="comment">//     System.out.println(it.next());</span></span><br><span class="line">    <span class="comment">//&#125;    </span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="迭代器的执行过程"><a href="#迭代器的执行过程" class="headerlink" title="迭代器的执行过程"></a>迭代器的执行过程</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">* An optimized version of AbstractList.Itr</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">private</span> <span class="class"><span class="keyword">class</span> <span class="title">Itr</span> <span class="keyword">implements</span> <span class="title">Iterator</span>&lt;<span class="title">E</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> cursor;       <span class="comment">// index of next element to return</span></span><br><span class="line">    <span class="keyword">int</span> lastRet = -<span class="number">1</span>; <span class="comment">// index of last element returned; -1 if no such</span></span><br><span class="line">    <span class="keyword">int</span> expectedModCount = modCount;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">hasNext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> cursor != size;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> E <span class="title">next</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        checkForComodification();</span><br><span class="line">        <span class="keyword">int</span> i = cursor;</span><br><span class="line">        <span class="keyword">if</span> (i &gt;= size)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> NoSuchElementException();</span><br><span class="line">        Object[] elementData = ArrayList.<span class="keyword">this</span>.elementData;</span><br><span class="line">        <span class="keyword">if</span> (i &gt;= elementData.length)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">        cursor = i + <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">return</span> (E) elementData[lastRet = i];</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">remove</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (lastRet &lt; <span class="number">0</span>)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException();</span><br><span class="line">        checkForComodification();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            ArrayList.<span class="keyword">this</span>.remove(lastRet);</span><br><span class="line">            cursor = lastRet;</span><br><span class="line">            lastRet = -<span class="number">1</span>;</span><br><span class="line">            expectedModCount = modCount;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (IndexOutOfBoundsException ex) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">forEachRemaining</span><span class="params">(Consumer&lt;? <span class="keyword">super</span> E&gt; consumer)</span> </span>&#123;</span><br><span class="line">        Objects.requireNonNull(consumer);</span><br><span class="line">        <span class="keyword">final</span> <span class="keyword">int</span> size = ArrayList.<span class="keyword">this</span>.size;</span><br><span class="line">        <span class="keyword">int</span> i = cursor;</span><br><span class="line">        <span class="keyword">if</span> (i &gt;= size) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">final</span> Object[] elementData = ArrayList.<span class="keyword">this</span>.elementData;</span><br><span class="line">        <span class="keyword">if</span> (i &gt;= elementData.length) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">while</span> (i != size &amp;&amp; modCount == expectedModCount) &#123;</span><br><span class="line">            consumer.accept((E) elementData[i++]);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// update once at end of iteration to reduce heap write traffic</span></span><br><span class="line">        cursor = i;</span><br><span class="line">        lastRet = i - <span class="number">1</span>;</span><br><span class="line">        checkForComodification();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">checkForComodification</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (modCount != expectedModCount)</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> ConcurrentModificationException();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>可以看到初始化的时候，<code>lastRet</code>的值为-1，说明迭代开始前，指针在第一个元素前一位。</li>
<li><code>hasNext</code>方法<ul>
<li><code>cursor</code>游标，记录当前指向的索引值(位置)，<code>cursor</code>初始化值为0。这里判断是游标是否走到了最大位置。</li>
<li><code>size</code>为集合初始化时的长度属性。</li>
</ul>
</li>
<li><code>next</code>方法<ul>
<li>首先判断了当前的游标位置是否超出了集合的最大位置，超出了就抛出对应的异常。</li>
<li>在下面首先将游标的值“++”操作，指向了下一个位置，并且返回了当前索引指向的元素</li>
</ul>
</li>
<li><code>int expectedModCount = modCount;</code><ul>
<li>由于<code>ArrayList</code>是线程不安全的，也就是在迭代的时候，还能对集合进行增删操作，这行代码实现了一个叫做“Fail-Fast(快速失败)机制”，在迭代的过程中有其他的线程修改了集合，就会抛出异常，快速失败。</li>
<li><code>modCount</code>是ArrayList中的一个属性，对集合中的增删操作都会进行<code>modCount++</code>操作，它保存了对这个集合操作的次数。</li>
<li><code>checkForComodification()</code>函数中对这个这个值进行了判断，看看是否在迭代的时候，对该集合进行了增删操作，所以如果两个值不一样，就会抛出异常。可以看到在<code>next</code>和<code>remove</code>的时候，都执行了该方法，就是对集合正确性的判断。</li>
<li>比如下面的代码中，在迭代的时候，对集合进行了增加操作，就会抛出异常<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span>(it.hasNext())&#123;</span><br><span class="line">    String s = it.next();</span><br><span class="line">    System.out.println(s);</span><br><span class="line">    coll.add(<span class="string">"haha"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ul>
<p><img src="http://ww1.sinaimg.cn/large/c55a7aeely1fmf7hlgxx2j20r709owek.jpg" alt=""></p>
<h3 id="集合迭代中的转型"><a href="#集合迭代中的转型" class="headerlink" title="集合迭代中的转型"></a>集合迭代中的转型</h3><ul>
<li><p>在使用集合时，我们需要注意以下几点：</p>
<ul>
<li>集合中存储其实都是对象的地址。</li>
<li>jdk1.5版本以后因为出现了基本类型包装类，它提供了自动装箱操作，这样，集合中的元素就是基本数值的包装类对象。</li>
</ul>
</li>
<li><p>集合存储时默认使用了Object作为储存元素的类型。也就是说集合中可以存储任何类型的数据</p>
<ul>
<li>下面的代码中，存储了String和int类型，然后在迭代的时候，进行强转的时候就会发生错误。<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Collection coll = <span class="keyword">new</span> ArrayList();</span><br><span class="line">coll.add(<span class="string">"123"</span>);</span><br><span class="line">coll.add(<span class="number">123</span>);</span><br><span class="line">Iterator it = coll.iterator();</span><br><span class="line"><span class="keyword">while</span> (it.hasNext()) &#123;</span><br><span class="line">    <span class="comment">//由于元素被存放进集合后全部被提升为Object类型</span></span><br><span class="line">    <span class="comment">//当需要使用子类对象特有方法时，需要向下转型</span></span><br><span class="line">    String str = (String) it.next();</span><br><span class="line">    System.out.println(str.length());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
<li><p>要灵活使用，就需要用到泛型</p>
<ul>
<li>泛型限制了集合中存储的对象的类型，在编译期就会检测出集合元素的类型，避免发生异常<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Collection&lt;String&gt; coll = <span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">coll.add(<span class="string">"123"</span>);</span><br><span class="line">coll.add(<span class="string">"456"</span>);</span><br><span class="line">Iterator it = coll.iterator();</span><br><span class="line"><span class="keyword">while</span> (it.hasNext()) &#123;</span><br><span class="line">    String str = it.next();</span><br><span class="line">    System.out.println(str.length());</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
</ul>
</li>
</ul>
<h3 id="foreach遍历数组"><a href="#foreach遍历数组" class="headerlink" title="foreach遍历数组"></a>foreach遍历数组</h3><ul>
<li>JDK1.5版本后,出现新的接口<code>java.lang.Iterable</code>，对于任何实现<code>Iterator</code>接口的对象都可以使用<code>foreach</code>遍历。</li>
<li>格式：<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">function</span><span class="params">()</span></span>&#123;</span><br><span class="line">    <span class="comment">//遍历数组</span></span><br><span class="line">    String[] str = &#123;<span class="string">"123"</span>,<span class="string">"456"</span>,<span class="string">"789"</span>&#125;;</span><br><span class="line">    <span class="keyword">for</span>(String s : str)&#123;</span><br><span class="line">        System.out.println(s.length());</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//遍历集合</span></span><br><span class="line">    ArrayList&lt;Student&gt; array = <span class="keyword">new</span> ArrayList&lt;Student&gt;();</span><br><span class="line">    array.add(<span class="keyword">new</span> Student(<span class="string">"zhangsan"</span>,<span class="number">22</span>));</span><br><span class="line">    array.add(<span class="keyword">new</span> Student(<span class="string">"lisi"</span>,<span class="number">11</span>));</span><br><span class="line">    <span class="keyword">for</span>(Person stu : array)&#123;</span><br><span class="line">        System.out.println(stu.name + <span class="string">"-----"</span> + stu.age);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>

      
    </div>
    <footer class="entry-meta entry-footer">
      
	<span class="ico-folder"></span>
    <a class="article-category-link" href="/categories/Java/">Java</a>

      
  <span class="ico-tags"></span>
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Java基础/">Java基础</a></li></ul>

      
        <div id="donation_div"></div>

<script src="/js/vdonate.js"></script>
<script>
var a = new Donate({
  title: '如果觉得我的文章对您有用，请随意打赏。您的支持将鼓励我继续创作!', // 可选参数，打赏标题
  btnText: 'Donate', // 可选参数，打赏按钮文字
  el: document.getElementById('donation_div'),
  wechatImage: '/css/images/wechatPay.png',
  alipayImage: '/css/images/alipay.jpg'
});
</script>
      

      
        
	<section id="comments" class="comment">
	  <div id="disqus_thread">
	  <noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
	  </div>
	</section>

	<script type="text/javascript">
	var disqus_shortname = 'haijdblog';
	(function(){
	  var dsq = document.createElement('script');
	  dsq.type = 'text/javascript';
	  dsq.async = true;
	  dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
	  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	}());
	(function(){
	  var dsq = document.createElement('script');
	  dsq.type = 'text/javascript';
	  dsq.async = true;
	  dsq.src = '//' + disqus_shortname + '.disqus.com/count.js';
	  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	}());
	</script>


      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2017/06/08/Java基础：泛型/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          Java基础：泛型
        
      </div>
    </a>
  
  
    <a href="/2017/06/01/Java基础：集合/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">Java基础：集合</div>
    </a>
  
</nav>

  
</article>

<!-- Table of Contents -->

  <aside id="sidebar">
    <div id="toc" class="toc-article">
    <strong class="toc-title">Contents</strong>
    
      <ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#迭代器的概述"><span class="nav-number">1.</span> <span class="nav-text">迭代器的概述</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#迭代器的实现原理"><span class="nav-number">2.</span> <span class="nav-text">迭代器的实现原理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#迭代器代码实现"><span class="nav-number">3.</span> <span class="nav-text">迭代器代码实现</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#迭代器的执行过程"><span class="nav-number">4.</span> <span class="nav-text">迭代器的执行过程</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#集合迭代中的转型"><span class="nav-number">5.</span> <span class="nav-text">集合迭代中的转型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#foreach遍历数组"><span class="nav-number">6.</span> <span class="nav-text">foreach遍历数组</span></a></li></ol>
    
    </div>
  </aside>
</section>
        
      </div>
      <footer id="footer" class="site-footer">
  

  <div class="clearfix container">
      <div class="site-info">
	      &copy; 2018 haijd All Rights Reserved.
          
            <span id="busuanzi_container_site_uv">
              本站访客数<span id="busuanzi_value_site_uv"></span>人次  
              本站总访问量<span id="busuanzi_value_site_pv"></span>次
            </span>
          
      </div>
      <div class="site-credit">
        Theme by <a href="https://github.com/iTimeTraveler/hexo-theme-hiero" target="_blank">hiero</a>
      </div>
  </div>
</footer>


<!-- min height -->

<script>
    var contentdiv = document.getElementById("content");

    contentdiv.style.minHeight = document.body.offsetHeight - document.getElementById("allheader").offsetHeight - document.getElementById("footer").offsetHeight + "px";
</script>
    </div>
    <!-- <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
    <a href="/categories" class="mobile-nav-link">Categories</a>
  
    <a href="/tags" class="mobile-nav-link">Tags</a>
  
    <a href="/about" class="mobile-nav-link">About</a>
  
</nav> -->
    

<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true
    }
  });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/scripts.js"></script>
<script src="/js/bootstrap.js"></script>
<script src="/js/main.js"></script>








	<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
	</script>






  </div>

  <a id="rocket" href="#top" class=""></a>
  <script type="text/javascript" src="/js/totop.js" async=""></script>
</body>
</html>
